<?php

namespace app\admin\controller;

use app\admin\model\UFlowdata;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 供应商新增/变更申请管理
 *
 */
class XCorpsq extends Backend
{
    /**
     * XCorpsq模型对象
     * @var \app\admin\model\XCorpsq
     */
    protected $model = null;
    
    protected $quickSearchField = ['BIZNO'];

    protected $defaultSortField = 'BIZNO,desc';
    protected $noNeedLogin      = ['*'];

    protected $preExcludeFields = [''];
    protected $flow=null;
    protected $corp=null;
    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XCorpsq;
        $this->flow =new \app\admin\model\UFlow();
        $this->corp=new \app\admin\model\Corplib();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $crop=$this->request->get('CORP');
        $wheres=[];
        if($crop){
            $wheres['CORP']=$crop;
        }
        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_corpsq.status',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }

        $adminInfo          = $this->auth->getInfo();
        $name='';
        if($adminInfo['id']!=1){
            $name='OP='.$adminInfo['nickname'];
        }
        $res = $this->model
            ->field(['*,dbo.f_getflowstatus(BIZNO) as status'])
//            ->field(['*'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($wheres)
            ->where($name)
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->field('*,dbo.f_getflowstatus(BIZNO) as statuss')->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }
    /**
     * @throws \think\db\exception\DbException
     * 审批列表页
     */
    public function index_s(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $crop=$this->request->get('CORP');
        $wheres=[];
        if($crop){
            $wheres['CORP']=$crop;
        }
        $status='';
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        foreach ($where as $k=>$item) {
            if(in_array('x_corpsq.status',$item)){
                $status=" dbo.f_getflowstatus(BIZNO) = '$item[2]'";
                unset($where[$k]);
            }
        }
        $adminInfo          = $this->auth->getInfo();
//        $adminInfo['id']='10016';
        //默认条件
        $m='';
        if($adminInfo['id']!=1){
            if(empty($where)){
                $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_corpsq.bizno    and iscurrent=1 and username='$adminInfo[nickname]') ";
            }else{
                $m="exists ( select * from u_flowdata where u_flowdata.bizno=x_corpsq.bizno     and username='$adminInfo[nickname]') ";
            }
        }


        $res = $this->model
            ->field(['*,dbo.f_getflowstatus(BIZNO) as status'])
//            ->field(['*'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($status)
            ->where($where)
            ->where($m)
            ->where($wheres)
            ->order($order)
            ->paginate($limit);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $data['BIZNO']='GY'. $this->microtime_format('YmdHisx',$this->microtime_float());
            //查询是否可以提交
               $status=$this->getcorpsq($data['CORP']);
            //根据公司查出部门
            $department=$this->corp->where('CORP',$data['CORP'])->value('DEPT');
            if($status==1){
                $result = false;
                Db::startTrans();
                try {
                    // 模型验证
                    if ($this->modelValidate) {
                        $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        if (class_exists($validate)) {
                            $validate = new $validate;
                            if ($this->modelSceneValidate) $validate->scene('add');
                            $validate->check($data);
                        }
                    }
                    $result = $this->model->save($data);

                    $this->createflowdata($data['BIZNO'],$department,'供应商审批',0);

                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success(__('Added successfully'));
                } else {
                    $this->error(__('No rows were added'));
                }
            }elseif ($status==2){
                $sp=$this->createflowdata($data['BIZNO'],$department,'供应商审批',0);
                if($sp==200){
                    $this->success(__('Added successfully'));
                }
                $this->error('创建失败');
            }else{
                $this->error('不能提交');
            }

        }

        $this->error(__('Parameter error'));
    }
    //审批记录
    public function flowdata(){
        $bizno=$this->request->get('bizno');
//        $bizno='2305BJ0004';
        $data=(new UFlowdata())->where('BIZNO',$bizno)->order('period','desc')->select()->toArray();
        $adminInfo          = $this->auth->getInfo();
        $this->success('', [
            'list'   => $data,
            'admin_id'  =>$adminInfo['id'],

        ]);
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 提交审批
     */
    public function flowdata_p(){
        $get=$this->request->get();
        $UFlowdata=new UFlowdata();
        $data=$UFlowdata->find($get['id']);

        $save=['STATUSFLAG'=>$get['status'],'STATUSTIME'=>date('Y-m-d H:i:s',time()),'ISCURRENT'=>'','NOTE'=>$get['note']];
        $one=$UFlowdata->where(['bizno'=>$data['BIZNO'],'period'=>$data['PERIOD']+1])->find();
        $res=false;
        Db::startTrans();
        try {
            $res= $data->save($save);

            if($one){
                $one->save(['ISCURRENT'=>1]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res) {
            $this->success(__('成功'));
        } else {
            $this->error(__('失败'));
        }

    }
}